<template>
<div class="loginContainer">
  <div class="content">
    <div class="mainContent">
      <h1>登录</h1>
      <el-form
          label-position="top"
          label-width="100px"
          :model="formLabelAlign"
          style="max-width: 460px;margin-top: 20px"
      >
        <el-form-item label="用户名">
          <el-input v-model="formLabelAlign.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formLabelAlign.password" type="password"/>
        </el-form-item>
      </el-form>
      <el-button
          type="primary"
          @click="login"
          :loading="loading"
          style="width: 100%;margin-top: 20px">登录</el-button>
      <el-link @click="gotoRegister">点我注册账号</el-link>
    </div>
  </div>
</div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import route from '@/router/index'
import {ElMessage} from "element-plus";
import axios from "axios";
import store from "@/store";

const loading = ref(false);
const formLabelAlign = reactive({
  username: '',
  password: ''
})
const gotoRegister = () => {
  route.push('/register')
}
const login = () => {
  loading.value = true
  if (formLabelAlign.username === '' || formLabelAlign.password === '') {
    ElMessage.error('用户名密码输入不合法')
    loading.value = false
  } else {
    axios.get(`/api/user/check/${formLabelAlign.username}/${formLabelAlign.password}`)
        .then((res) => {
          if (res.data === 200) {
            axios.get(`/api/user/${formLabelAlign.username}/${formLabelAlign.password}`)
                .then(res => {
                  store.state.user = res.data[0]
                })
                .finally(() => {
                  ElMessage.success('登陆成功')
                  route.push('/')
                  loading.value = false
                })
          } else {
            ElMessage.error('账户名密码不正确')
            loading.value = false
          }
        })
  }
}
</script>

<style scoped>
.loginContainer{
  width: 100%;
  height: 100%;
  background-color: var(--el-backtop-bg-color);
  display: flex;
  justify-content: center;
}
.content{
  margin-top: 50px;
  width: 500px;
  height: 500px;
  border: #1a1a1a solid 1px;
}
.mainContent{
  width: 80%;
  height: 80%;
  margin-left: 10%;
  margin-top: 10%;
}
</style>